package com.example.oracle.tool;

import com.example.oracle.pojo.User;
import com.example.oracle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * @author Siaze
 * @date 2021/11/21
 */

@Component
public class MailUtil {

    @Autowired
    JavaMailSender sender;

    @Value("${spring.mail.username}")
    String mainMail;

    @Autowired
    UserService userService;

    public static final String ADMIN_EMAIL = "siaze@qq.com";
    /**
     * 发送邮件
     * @param user 发送的邮箱
     * @param context 发送的内容
     */
    public void sendMessage(String user,String context){
        try{
            MimeMessage mimeMessage = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            // 一般是用户的邮箱号
            helper.setFrom(mainMail);
            // 发送的主题
            helper.setSubject("校园跑腿服务平台");
            // 接受者用户，也可发送多个用户（String[]）
            helper.setTo(user);
            // 内容
            helper.setText(context);
            // 发送
            sender.send(mimeMessage);
            System.out.println("successful");
        }catch (Exception e){
            System.out.println("error");
        }
    }

    public void sendMessageToAdmin(String context){
        sendMessage(ADMIN_EMAIL, context);
    }

    /**
     * 通过用户ID查询邮箱，并发送信息
     * @param userId 用户ID
     * @param context 邮箱内容
     */
    public void sendMessage(long userId,String context) {
        User user = new User();
        user.setId(userId);
        List<User> users = userService.getUsers(user);
        if (users.size() > 0 && StringUtils.hasLength(users.get(0).getEmail())) {
            sendMessage(users.get(0).getEmail(), context);
        }
    }
}
